<template>
  <div>
    <a-spin :spinning="spinning" tip="Loading...">
      <a-form-model
        ref="form"
        :model="form.val"
        :rules="form.rules"
        :label-col="form.labelCol"
        :wrapper-col="form.wrapperCol"
      >
        <a-form-model-item label="名称" prop="name">
          <a-input v-model="form.val.name" placeholder="请输入" />
        </a-form-model-item>
        <a-form-model-item v-if="!isRootNode" label="上级" prop="parentId">
          <a-cascader
            v-model="form.val.parentId"
            changeOnSelect
            :field-names="{ label: 'name', value: 'id', children: 'children' }"
            :options="menuOptions"
            placeholder="请选择"
          />
        </a-form-model-item>
        <a-form-model-item label="类型" prop="type">
          <a-radio-group v-model="form.val.type" :disabled="isRootNode" @change="handleTypeChange">
            <a-radio :value="0">目录</a-radio>
            <a-radio :value="1">菜单</a-radio>
            <a-radio :value="2">业务</a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="路由地址" prop="path">
          <a-input v-model="form.val.path" :disabled="isRootNode" placeholder="请输入" />
        </a-form-model-item>
        <a-form-model-item v-if="form.val.type == 1" prop="isOutside">
          <span slot="label">
            <a-tooltip title="若选择是外链，需输入外链地址">
              <a-icon type="question-circle-o" />
            </a-tooltip>
            是否外链
          </span>
          <a-radio-group v-model="form.val.isOutside" :disabled="isRootNode" @change="handleHrefChange">
            <a-radio :value="0">否</a-radio>
            <a-radio :value="1">是</a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item v-if="form.val.isOutside == 1" prop="component">
          <span slot="label">
            <a-tooltip title="外链地址需要以'http(s)://'开头">
              <a-icon type="question-circle-o" />
            </a-tooltip>
            外链地址
          </span>
          <a-input v-model="form.val.component" :disabled="isRootNode" placeholder="请输入" />
        </a-form-model-item>
        <a-form-model-item v-if="form.val.type != 0 && form.val.isOutside != 1" label="组件" prop="component">
          <a-input v-model="form.val.component" :disabled="isRootNode" placeholder="请输入" />
        </a-form-model-item>
        <a-form-model-item v-if="form.val.type != 0" label="打开方式" prop="target">
          <a-select v-model="form.val.target" placeholder="请选择" :disabled="isRootNode">
            <a-select-option v-for="item in targetMap" :key="item.key" :value="item.key">{{ item.value }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="图标" prop="icon">
          <a-button v-if="form.val.icon" type="primary" :icon="form.val.icon" @click="openIconModal"></a-button>
          <a-button v-else type="primary" @click="openIconModal">选择</a-button>
        </a-form-model-item>
        <a-form-model-item v-if="(form.val.type == 0 || form.val.type == 1) && form.val.isOutside == 0" label="重定向" prop="redirect">
          <a-input v-model="form.val.redirect" placeholder="请输入" />
        </a-form-model-item>
        <a-form-model-item label="排序" prop="sort">
          <a-input v-model.number="form.val.sort" style="width:100%" oninput="value=value.replace(/\D/g,'')" placeholder="请输入" />
        </a-form-model-item>
        <a-form-model-item v-if="form.val.type != 2" label="状态" prop="hidden">
          <a-select v-model="form.val.hidden" placeholder="请选择">
            <a-select-option :value="0">显示</a-select-option>
            <a-select-option :value="1">隐藏</a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-spin>
    <a-form-item class="form-btn">
      <a-button @click="closeDetail(false)">取消</a-button>
      <a-button type="primary" :loading="form.confirmLoading" @click="onSubmit('form')">确定</a-button>
    </a-form-item>

    <!-- 图标选择 -->
    <a-modal :visible="iconModal.show" title="菜单图标库" @cancel="iconModal.show = false" @ok="handleModalOk">
      <icon-selector v-model="iconModal.icon" @change="handleIconChange"/>
    </a-modal>
  </div>
</template>

<script>
import { getMenuInfo, createMenuInfo, updateMenuInfo } from '@/api/system'
import { findAllParent } from '@/utils/util'
import IconSelector from '@/components/IconSelector'

export default {
  components: {
    IconSelector
  },
  props: {
    currentInfo: {
      type: Object,
      required: true
    },
    menuOptions: {
      type: Array,
      required: true
    }
  },
  data () {
    return {
      isRootNode: false,
      targetMap: [{
        key: '',
        value: '当前页'
      }, {
        key: '_blank',
        value: '新标签页'
      }],
      spinning: false,
      iconModal: {
        show: false,
        icon: ''
      },
      form: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 19 }
        },
        confirmLoading: false,
        val: {},
        rules: {
          name: [{ required: true, message: '名称不可为空', trigger: 'blur' }],
          path: [{ required: true, message: '链接不可为空', trigger: 'blur' }],
          component: [{ required: true, message: '组件不可为空', trigger: 'blur' }],
          status: [{ required: true, message: '状态不可为空', trigger: 'change' }],
          type: [{ required: true, message: '类型不可为空', trigger: 'change' }],
          isOutside: [{ required: true, message: '不可为空', trigger: 'change' }],
          parentId: [{ required: true, message: '上级不可为空', trigger: 'change' }]
        }
      }
    }
  },
  watch: {
    'currentInfo.id': {
      handler: 'resetForm',
      immediate: true
    }
  },
  methods: {
    // 重构表单内容
    resetForm (val) {
      this.form.confirmLoading = false
      this.$nextTick(() => { // 清除表单验证结果
        this.$refs.form.clearValidate()
      })

      if (this.currentInfo.isAdd) {
        const path = new Date().getTime()
        this.form.val = { path, hidden: 0, target: '', type: 0, isOutside: 0 }
        this.isRootNode = false
      } else {
        this.getInfo(val)
      }
    },
    // 获取详情
    getInfo (id) {
      this.spinning = true
      getMenuInfo({ id }).then(res => {
        const { name, parentId, path, component, icon, hidden, isOutside, redirect, sort, target, type, des } = res.content || {}
        this.isRootNode = parentId === 0
        const basic = { id, name, path, icon, redirect, sort, component, des }
        const parentIds = this.getMenuParentIds({ id, parentId }, this.menuOptions)
        this.form.val = {
          ...basic,
          parentId: parentIds.length === 0 ? undefined : parentIds.reverse(),
          isOutside: isOutside || 0,
          type: type || 0,
          hidden: hidden ? 1 : 0,
          target: target || ''
        }
      }).finally(res => {
        this.spinning = false
      })
    },
    // 是否外链
    handleHrefChange (val) {
      this.$set(this.form.val, 'component', undefined)
    },
    handleTypeChange (val) {
      // const { type } = this.form.val
      this.$set(this.form.val, 'isOutside', 0)
    },
    // 打开图标选择
    openIconModal () {
      const { icon } = this.form.val
      this.iconModal = {
        show: true,
        icon: icon || 'desktop'
      }
    },
    // 监听图标选择
    handleIconChange (val) {
      this.$set(this.iconModal, 'icon', val)
    },
    // 确定图标选择
    handleModalOk () {
      const { icon } = this.iconModal
      this.$set(this.form.val, 'icon', icon)
      this.iconModal.show = false
    },
    // 获取 pids
    getMenuParentIds (node, menuTreeData) {
      const nodes = []
      const parentNodes = findAllParent(node, menuTreeData, nodes)
      return parentNodes.map(item => item.id)
    },
    // 关闭弹出框
    closeDetail (val) {
      this.form.confirmLoading = false
      this.$emit('emitToParent', val)
    },
    // 提交表单信息
    onSubmit (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.form.confirmLoading = true
          const fetchFun = this.currentInfo.isAdd ? createMenuInfo : updateMenuInfo
          const { parentId } = this.form.val
          const params = {
            ...this.form.val,
            parentId: parentId && parentId.length ? parentId[parentId.length - 1] : 0
          }
          if (params.type === 0 && params.isOutside === 0) {
            params.component = 'BlankLayout'
          }
          if (params.type === 2) {
            params.hidden = 1
          }
          this.updateInfo(fetchFun, params)
        }
      })
    },
    // 修改表单信息接口相应
    updateInfo (fetchFun, params) {
      fetchFun(params).then(response => {
        this.$message.success((params.id ? '修改' : '新增') + '成功！')
        this.closeDetail(true)
      }).finally(() => {
        this.form.confirmLoading = false
      })
    }
  }
}
</script>
